import { app, shell, BrowserWindow, ipcMain, Menu } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

const login_width = 530
const register_height = 635

function createContextMenu(window) {
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '开发者工具',
      click: () => window.webContents.openDevTools()
    },
    { type: 'separator' },
    {
      label: '刷新页面',
      click: () => window.webContents.reload()
    }
  ])

  window.webContents.on('context-menu', (_, params) => {
    contextMenu.popup()
  })
}

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    icon: icon,
    width: login_width,
    height: register_height,
    show: false,
    transparent: true,
    autoHideMenuBar: true,
    titleBarStyle: 'hidden',
    resizable: false,
    frame: true,
    mediaAccess: true,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: false,
      webSecurity: false
    }
  })

  // 设置CSP规则，允许所有源
  mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    const newHeaders = {
      ...details.responseHeaders,
      'Content-Security-Policy': ['default-src \'self\' blob: data: *; connect-src \'self\' http://localhost:* https://* ws://* wss://* blob: data:; script-src \'self\' \'unsafe-inline\' \'unsafe-eval\'; style-src \'self\' \'unsafe-inline\''],
      'Access-Control-Allow-Origin': ['*']
    }
    callback({
      responseHeaders: newHeaders
    })
  })
  ipcMain.on('toMain', (event, args) => {
    mainWindow.setResizable(true)
    mainWindow.setSize((args.screenWidth / 5) * 3 + 150, 600)
    mainWindow.setMinimumSize((args.screenWidth / 5) * 3 + 150, 600)
    mainWindow.center()
    mainWindow.setMaximizable(true)
    mainWindow.setMaximumSize((args.screenWidth / 5) * 4 + 200, (args.screenHeight / 5) * 4)
  })

  ipcMain.on('minimizing', (event, args) => {
    event.preventDefault() // 阻止默认最小化行为
    mainWindow.minimize() // 最小化到任务栏
  })

  ipcMain.on('expandWindow', (event, args) => {
    let currentSize = mainWindow.getSize()
    if (currentSize[0] === (args.screenWidth / 5) * 4 + 200 && currentSize[1] === (args.screenHeight / 5) * 4) {
      // 当前是大窗口，点击后变小
      mainWindow.setResizable(true)
      mainWindow.setSize((args.screenWidth / 5) * 3 + 150, 600)
    } else {
      // 当前是小窗口，点击后变大
      mainWindow.setResizable(true)
      mainWindow.setSize((args.screenWidth / 5) * 4 + 200, (args.screenHeight / 5) * 4)
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // 注册右键菜单
  createContextMenu(mainWindow)

  // 注册开发者工具快捷键
  mainWindow.webContents.on('before-input-event', (event, input) => {
    if (input.control && input.key.toLowerCase() === 'i') {
      mainWindow.webContents.openDevTools()
      event.preventDefault()
    }
  })
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
